package com.xiaoxu.intranetweb.mybatisplusSzappdb.business.product;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.Dic.PdtAuthDic;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.log.SysLogBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.GetPriceRecordExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.PdtAuthExcelEn;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.service.*;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.Constructor.TPriceRecord2GetPriceRecordVo;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.vo.GetPriceRecordVo;
import com.xiaoxu.intranetweb.util.SzResult;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Future;

import static com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.GetPriceRecordExcelEn.*;

@Component
public class PdtAuthBu {
    @Autowired
    private ICPdtsAuthService iCPdtsAuthService;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private SysLogBu sysLogBu;
    @Autowired
    private PdtAuthDic pdtAuthDic;
    @Autowired
    private ITPriceRecordService itPriceRecordService;
    @Autowired
    private ICProductsInfoService icProductsInfoService;
    @Autowired
    private ICCompanysService icCompanysService;
    @Autowired
    private TPriceRecord2GetPriceRecordVo tPriceRecord2GetPriceRecordVo;
    @Autowired
    private ICPdtsAuthService icPdtsAuthService;
    @Autowired
    private ICOrderDetailService iCOrderDetailService;
    @Autowired
    private ICCompanysService iCCompanysService;
    @Autowired
    private ICProductsInfoService iCProductsInfoService;
    @Autowired
    private ICWeightSheetsService icWeightSheetsService;
    @Autowired
    private ICOrderDetailService icOrderDetailService;
    @Autowired
    private ICTrucksService iCTrucksService;
    @Autowired
    private ITApproveService approveService;
    @Autowired
    private ITApproveInfoService approveInfoService;
    //    所有品种授权

    /**
     * 根据单位类型返回所有该类型的单位
     *
     * @param page     页码
     * @param pageSize 每页条数
     * @param pdt      品种名称
     * @return 返回所有该类型的单位
     */
    public SzResult getPdtAuth(String page, String pageSize, String co, String chiCo, String pdt, String token, String plantId) throws Exception {
        Map<String,Object> map = new HashMap<>();
//       co1为公司名加子公司名，中间用.隔开
//        String co = null;
//        String chiCo = null;

//        if (co1 != null && !co1.equals("")) {
//            co = co1.substring(0, co1.indexOf("."));
//            chiCo = co1.substring(co1.indexOf(".") + 1);
//        }
        if (page != null && !page.isEmpty() && pageSize != null && !pageSize.isEmpty()) {
            Page<CPdtsAuth> page1 = new Page<>(Integer.parseInt(page), Integer.parseInt(pageSize));
            QueryWrapper<CPdtsAuth> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(co != null && !co.isEmpty(), "PDTSAUTH_CO", co);
            queryWrapper.eq(chiCo != null && !chiCo.isEmpty(), "PDTSAUTH_CHICO", chiCo);
            queryWrapper.eq(pdt != null && !pdt.isEmpty(), "PDTSAUTH_PDT", pdt);
            queryWrapper.eq("PDTSAUTH_DELETED", 0);
            queryWrapper.eq("DATA_FROM", plantId);
            queryWrapper.orderByAsc("PDTSAUTH_LOCK");
            queryWrapper.orderByDesc("PDTSAUTH_ID");
            List<CPdtsAuth> totalList = iCPdtsAuthService.list(queryWrapper);
            Iterator<CPdtsAuth> iterator = totalList.iterator();
            while (iterator.hasNext()) {
                CPdtsAuth cPdtsAuth = iterator.next();
                String pdtsauthCo = cPdtsAuth.getPdtsauthCo();
                String pdtsauthChico = cPdtsAuth.getPdtsauthChico();
                QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("CPY_CO", pdtsauthCo);
                queryWrapper1.eq("CPY_CHICO", pdtsauthChico);
                queryWrapper1.eq("CPY_DELETED", 0);
                CCompanys cCompanys = icCompanysService.getOne(queryWrapper1);
                if (cCompanys == null) {
                    iterator.remove();
                }
            }
            int total = totalList.size();
            int start = (Integer.parseInt(page) - 1) * Integer.parseInt(pageSize);
            int end = Integer.parseInt(page) * Integer.parseInt(pageSize);
            List<CPdtsAuth> list = new ArrayList<>();
            for (int i = start; i < end && i < total; i++) {
                if (i < totalList.size()) {
                    list.add(totalList.get(i));
                }
            }
            map.put("total", total);
            map.put("list", list);
        } else {
            QueryWrapper<CPdtsAuth> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(co != null, "PDTSAUTH_CO", co);
            queryWrapper.eq(chiCo != null && !chiCo.equals(""), "PDTSAUTH_CHICO", chiCo);
            queryWrapper.eq(pdt != null && !pdt.equals(""), "PDTSAUTH_PDT", pdt);
            queryWrapper.orderByAsc("PDTSAUTH_LOCK");
            queryWrapper.orderByDesc("PDTSAUTH_ID");
            queryWrapper.eq("PDTSAUTH_DELETED", 0);
            queryWrapper.eq("DATA_FROM", plantId);
            List<CPdtsAuth> list = iCPdtsAuthService.list(queryWrapper);
            for (CPdtsAuth cPdtsAuth : list) {
                String pdtsauthCo = cPdtsAuth.getPdtsauthCo();
                String pdtsauthChico = cPdtsAuth.getPdtsauthChico();
                QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("CPY_CO", pdtsauthCo);
                queryWrapper1.eq("CPY_CHICO", pdtsauthChico);
                queryWrapper1.eq("CPY_DELETED", 0);
                CCompanys cCompanys = icCompanysService.getOne(queryWrapper1);
                if (cCompanys != null) {
                    list.remove(cPdtsAuth);
                }
            }
            map.put("total", list.size());
            map.put("list", list);
        }
        return SzResult.success(map);
    }


    /**
     * 新增品种授权
     *
     * @param pdtsauthCo    授权单位
     * @param pdtsauthPdt   授权子单位
     * @param pdtsauthPrice 授权品种
     * @param pdtsauthChico 授权价格
     * @param token         授权人
     */
    public SzResult addPdtAuth(String pdtsauthCo, String pdtsauthChico, String pdtsauthPdt, String pdtsauthPrice, String token, String plantId) throws Exception {
        // String plantId = plantId;
      String uuid = java.util.UUID.randomUUID().toString().replace("-", "");
      LocalDateTime now = LocalDateTime.now();
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        QueryWrapper<CPdtsAuth> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PDTSAUTH_CO", pdtsauthCo);
        queryWrapper.eq("PDTSAUTH_CHICO", pdtsauthChico);
        queryWrapper.eq("PDTSAUTH_PDT", pdtsauthPdt);
        queryWrapper.eq("PDTSAUTH_DELETED", 0);
        List<CPdtsAuth> list = iCPdtsAuthService.list(queryWrapper);
        if (list.size()>0) {
            return SzResult.error("该单位已授权该品种，请勿重复授权");
        }
        CPdtsAuth cPdtsAuth = new CPdtsAuth();
        cPdtsAuth.setId(uuid);
        QueryWrapper<CPdtsAuth> pdtsAuthQueryWrapper = new QueryWrapper<>();
        pdtsAuthQueryWrapper.orderByDesc("PDTSAUTH_ID");
        pdtsAuthQueryWrapper.last("limit 1");
        pdtsAuthQueryWrapper.eq("DATA_FROM", plantId);
        CPdtsAuth pdtsAuth = iCPdtsAuthService.getOne(pdtsAuthQueryWrapper);
        if (pdtsAuth != null) {
            BigDecimal pdtsauthId = pdtsAuth.getPdtsauthId();
            String pdtsauthId1 = String.valueOf((pdtsauthId.intValue() + 1));
            cPdtsAuth.setPdtsauthId(new BigDecimal(pdtsauthId1));
        } else {
            cPdtsAuth.setPdtsauthId(new BigDecimal(1));
        }
        cPdtsAuth.setPdtsauthCo(pdtsauthCo);
        cPdtsAuth.setPdtsauthChico(pdtsauthChico);
        cPdtsAuth.setPdtsauthPdt(pdtsauthPdt);
        if (pdtsauthPrice != null && !pdtsauthPrice.isEmpty()) {
            cPdtsAuth.setPdtsauthPrice(new BigDecimal(pdtsauthPrice));
        }
        cPdtsAuth.setPdtsauthOprtr(user.getTrueName());
        cPdtsAuth.setPdtsauthTime(LocalDateTime.now());
        cPdtsAuth.setDataFrom(plantId);
        cPdtsAuth.setPdtsauthDeleted(0);
        cPdtsAuth.setPdtsauthLock(0);
        cPdtsAuth.setDownedID1(0);
        cPdtsAuth.setPdtsauthReason("授权");
        cPdtsAuth.setSvrTmstamp(now);
        cPdtsAuth.setCliTmstamp(now);
        cPdtsAuth.setPdtsauthNew(1);
        //该品种绑定的单位就是收款单位
        QueryWrapper<CProductsInfo> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("PDTINF_PDT", pdtsauthPdt);
        queryWrapper3.eq("PDTINF_DELETED", 0);
        CProductsInfo cProductsInfo = iCProductsInfoService.getOne(queryWrapper3);
        String pdtinfSubjectId = cProductsInfo.getPdtinfSubjectId();
        if (pdtinfSubjectId == null) {
            return SzResult.error("该品种未绑定单位，请先绑定单位");
        }
        //审批
        QueryWrapper<TApprove> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("IF_ON", 1);
        queryWrapper4.eq("DEL_FLAG", 0);
        queryWrapper4.eq("DATA_FROM", plantId);
        queryWrapper4.eq("APPROVE_NAME", "pdtAuth");
        TApprove tApprove = approveService.getOne(queryWrapper4);

        if (tApprove != null) {//开启了审批，创建审批信息
            TApproveInfo tApproveInfo = new TApproveInfo();
            tApproveInfo.setApproveId(tApprove.getId());
            tApproveInfo.setApproveTier(tApprove.getApproveTier());
            tApproveInfo.setApproveState(0);
            tApproveInfo.setCreateBy(user.getTrueName());
            tApproveInfo.setCreateTime(LocalDateTime.now());
            tApproveInfo.setDelFlag(0);
            tApproveInfo.setApproveRemark("");
            tApproveInfo.setApproveInfo("由【" + user.getTrueName() + "】发起的品种授权审批：【" + "将" + pdtsauthPdt + "授权给" + pdtsauthCo + "." + pdtsauthChico + " 单位" + "授权价格为:" + pdtsauthPrice + " 】");
            tApproveInfo.setDataFrom(plantId);
            Map<String, Object> map = new HashMap<>();
            map.put("cPdtsAuth", cPdtsAuth);
            map.put("pdtinfSubjectId", pdtinfSubjectId);
            String s = JSON.toJSONString(map);
            tApproveInfo.setExecutionData(s);
            approveInfoService.save(tApproveInfo);
            return SzResult.Error("该功能需审批,请等待审批");
        }
        iCPdtsAuthService.save(cPdtsAuth);
        return SzResult.Success();
    }

    //    产品调价
    @Transactional
    public SzResult updatePdtPrice(List<String> id, String price, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //String plantId = plantId;
        if (user != null) {
            QueryWrapper<CWeightSheets> weightSheetsQueryWrapper = new QueryWrapper<>();
            weightSheetsQueryWrapper.eq("WEISHT_DEDUCTION",0);
            weightSheetsQueryWrapper.isNull("WEISHT_FULL_TM");
            weightSheetsQueryWrapper.eq("WEISHT_BACKED",1);
            weightSheetsQueryWrapper.eq("WEISHT_DELETED",0);
            if (icWeightSheetsService.list(weightSheetsQueryWrapper).size() != 0) {
                return SzResult.error("还有未扣款单据，请稍后重新价");
            }
            StringBuilder logMsg = new StringBuilder();
            StringBuilder logMsg1 = new StringBuilder();
            for (String s : id) {
                QueryWrapper<CPdtsAuth> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("ID", s);
                queryWrapper.eq("PDTSAUTH_DELETED", 0);
                CPdtsAuth cPdtsAuth = iCPdtsAuthService.getOne(queryWrapper);
                if (cPdtsAuth == null) {
                    return SzResult.error("该授权信息不存在");
                }
                logMsg1.append("调整").append(cPdtsAuth.getPdtsauthCo()).append("的").append(cPdtsAuth.getPdtsauthPdt()).append("价格由").append(cPdtsAuth.getPdtsauthPrice()).append("调整为").append(price).append(";\n");
                ;

            }

            //审批
            QueryWrapper<TApprove> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq("IF_ON", 1);
            queryWrapper3.eq("DEL_FLAG", 0);
            queryWrapper3.eq("DATA_FROM", plantId);
            queryWrapper3.eq("APPROVE_NAME", "updatePdtPrice");
            TApprove tApprove = approveService.getOne(queryWrapper3);

            if (tApprove != null) {//开启了审批，创建审批信息
                TApproveInfo tApproveInfo = new TApproveInfo();
                tApproveInfo.setApproveId(tApprove.getId());
                tApproveInfo.setApproveTier(tApprove.getApproveTier());
                tApproveInfo.setApproveState(0);
                tApproveInfo.setCreateBy(user.getTrueName());
                tApproveInfo.setCreateTime(LocalDateTime.now());
                tApproveInfo.setDelFlag(0);
                tApproveInfo.setApproveRemark("");
                tApproveInfo.setApproveInfo(logMsg.toString());
                tApproveInfo.setDataFrom(plantId);
                Map<String, Object> map = new HashMap<>();
                map.put("userId", user.getId());
                map.put("trueName", user.getTrueName());
                map.put("price", price);
                map.put("plantId", plantId);
                map.put("ids", id);
                String s = JSON.toJSONString(map);
                tApproveInfo.setExecutionData(s);
                tApproveInfo.setApproveInfo("由【" + user.getTrueName() + "】发起的产品调价审批：\n【" + logMsg1 + " 】");
                approveInfoService.save(tApproveInfo);
                return SzResult.Error("该功能需审批,请等待审批");
            }


            for (String s : id) {
                QueryWrapper<CPdtsAuth> authQueryWrapper = new QueryWrapper<>();
                authQueryWrapper.eq("ID", s);
                CPdtsAuth cPdtsAuth = iCPdtsAuthService.getOne(authQueryWrapper);
                cPdtsAuth.setPdtsauthReason(LocalDateTime.now().toString().replace("T"," ") + "由" + user.getTrueName() + "调价：" + cPdtsAuth.getPdtsauthPrice() + "->" + price);
//                "调整" + cPdtsAuth.getPdtsauthCo() + "的" + cPdtsAuth.getPdtsauthPdt() + "价格由" + cPdtsAuth.getPdtsauthPrice() + "调整为" + price
                logMsg.append("调整").append(cPdtsAuth.getPdtsauthCo()).append("的").append(cPdtsAuth.getPdtsauthPdt()).append("价格由").append(cPdtsAuth.getPdtsauthPrice()).append("调整为").append(price);
                cPdtsAuth.setPdtsauthPrice(BigDecimal.valueOf(Double.parseDouble(price)));
                cPdtsAuth.setPdtsauthOprtr(user.getTrueName());
                cPdtsAuth.setPdtsauthTime(LocalDateTime.now());
                iCPdtsAuthService.updateById(cPdtsAuth);
                String recordNo = LocalDateTime.now().getYear() + String.valueOf(LocalDateTime.now().getMonthValue() < 10 ? "0" + LocalDateTime.now().getMonthValue() : LocalDateTime.now().getMonthValue()) + (LocalDateTime.now().getDayOfMonth() < 10 ? "0" + LocalDateTime.now().getDayOfMonth() : LocalDateTime.now().getDayOfMonth());
//                拿到TPriceRecord表里RECORD_ID的最大值
                QueryWrapper<TPriceRecord> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.like("RECORD_NO", recordNo);
                queryWrapper2.orderByDesc("RECORD_NO");
                queryWrapper2.last("limit 1");
                TPriceRecord tPriceRecord1 = itPriceRecordService.getOne(queryWrapper2);
                TPriceRecord tPriceRecord = new TPriceRecord();
                tPriceRecord.setPrice(BigDecimal.valueOf(Double.parseDouble(price)));
                QueryWrapper<CProductsInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("PDTINF_PDT", cPdtsAuth.getPdtsauthPdt());
                queryWrapper.eq("PDTINF_DELETED", 0);
                CProductsInfo cProductsInfo = icProductsInfoService.getOne(queryWrapper);
                tPriceRecord.setPdtId(cProductsInfo.getId());
                tPriceRecord.setCreateTime(LocalDateTime.now());
                tPriceRecord.setCreatorId(user.getId());
                QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("CPY_CO", cPdtsAuth.getPdtsauthCo());
                queryWrapper1.eq("CPY_CHICO", cPdtsAuth.getPdtsauthChico());
                queryWrapper1.eq("CPY_DELETED", 0);
                CCompanys cCompanys = icCompanysService.getOne(queryWrapper1);
                tPriceRecord.setCpyId(cCompanys.getId());
                tPriceRecord.setCreatorName(user.getTrueName());
                if (tPriceRecord1 == null) {
                    tPriceRecord.setRecordNo(BigDecimal.valueOf(Long.parseLong(recordNo + "0001")));
                } else {
                    tPriceRecord.setRecordNo(BigDecimal.valueOf(Long.parseLong(tPriceRecord1.getRecordNo().toString()) + 1));
                }
                tPriceRecord.setDataFrom(plantId);
                itPriceRecordService.save(tPriceRecord);
            }
            sysLogBu.logRecord("产品调价", user.getTrueName(), String.valueOf(logMsg), plantId);
            return SzResult.Success();
        } else {
            return SzResult.error("用户不存在");
        }
    }

    //    一键调价
    @Transactional
    public SzResult updatePdtPriceAll(String token, String pdtInfPrice, String pdt, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        //  String plantId = plantId;
        if (user != null) {
            QueryWrapper<CWeightSheets> weightSheetsQueryWrapper = new QueryWrapper<>();
            weightSheetsQueryWrapper.eq("WEISHT_DEDUCTION",0);
            weightSheetsQueryWrapper.isNull("WEISHT_FULL_TM");
            weightSheetsQueryWrapper.eq("WEISHT_BACKED",1);
            weightSheetsQueryWrapper.eq("WEISHT_DELETED",0);
            if (icWeightSheetsService.list(weightSheetsQueryWrapper).size() != 0) {
                return SzResult.error("还有未扣款单据，请稍后重新价");
            }
            StringBuilder logMsg = new StringBuilder();
            QueryWrapper<CPdtsAuth> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.eq(pdt != null && !pdt.equals(""), "PDTSAUTH_PDT", pdt);
            queryWrapper3.orderByAsc("PDTSAUTH_CO");
            queryWrapper3.eq("PDTSAUTH_DELETED", 0);
            queryWrapper3.eq("DATA_FROM", plantId);
            List<CPdtsAuth> list = iCPdtsAuthService.list(queryWrapper3);
            for (CPdtsAuth cPdtsAuth : list) {
                cPdtsAuth.setPdtsauthReason(LocalDateTime.now() + "由" + user.getTrueName() + "调价" + cPdtsAuth.getPdtsauthPrice() + "->" + pdtInfPrice);
                cPdtsAuth.setPdtsauthReason("调整" + cPdtsAuth.getPdtsauthCo() + "的" + cPdtsAuth.getPdtsauthPdt() + "价格由" + cPdtsAuth.getPdtsauthPrice() + "调整为" + pdtInfPrice);
                logMsg.append("调整").append(cPdtsAuth.getPdtsauthCo()).append("的").append(cPdtsAuth.getPdtsauthPdt()).append("价格由").append(cPdtsAuth.getPdtsauthPrice()).append("调整为").append(pdtInfPrice);
                cPdtsAuth.setPdtsauthPrice(BigDecimal.valueOf(Double.parseDouble(pdtInfPrice)));
                cPdtsAuth.setPdtsauthOprtr(user.getTrueName());
                cPdtsAuth.setPdtsauthTime(LocalDateTime.now());
                iCPdtsAuthService.updateById(cPdtsAuth);
                String recordNo = LocalDateTime.now().getYear() + String.valueOf(LocalDateTime.now().getMonthValue() < 10 ? "0" + LocalDateTime.now().getMonthValue() : LocalDateTime.now().getMonthValue()) + (LocalDateTime.now().getDayOfMonth() < 10 ? "0" + LocalDateTime.now().getDayOfMonth() : LocalDateTime.now().getDayOfMonth());
//                拿到TPriceRecord表里RECORD_ID的最大值
                QueryWrapper<TPriceRecord> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.like("RECORD_NO", recordNo);
                queryWrapper2.orderByDesc("RECORD_NO");
                queryWrapper2.last("limit 1");
                TPriceRecord tPriceRecord1 = itPriceRecordService.getOne(queryWrapper2);
                TPriceRecord tPriceRecord = new TPriceRecord();
                tPriceRecord.setPrice(BigDecimal.valueOf(Double.parseDouble(pdtInfPrice)));
                QueryWrapper<CProductsInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("PDTINF_PDT", cPdtsAuth.getPdtsauthPdt());
                queryWrapper.eq("PDTINF_DELETED", 0);
                CProductsInfo cProductsInfo = icProductsInfoService.getOne(queryWrapper);
                tPriceRecord.setPdtId(cProductsInfo.getId());
                tPriceRecord.setCreateTime(LocalDateTime.now());
                tPriceRecord.setCreatorId(user.getId());
                QueryWrapper<CCompanys> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("CPY_CO", cPdtsAuth.getPdtsauthCo());
                queryWrapper1.eq("CPY_CHICO", cPdtsAuth.getPdtsauthChico());
                queryWrapper1.eq("CPY_DELETED", 0);
                CCompanys cCompanys = icCompanysService.getOne(queryWrapper1);
                tPriceRecord.setCpyId(cCompanys.getId());
                tPriceRecord.setCreatorName(user.getTrueName());
                if (tPriceRecord1 == null) {
                    tPriceRecord.setRecordNo(BigDecimal.valueOf(Long.parseLong(recordNo + "0001")));
                } else {
                    tPriceRecord.setRecordNo(BigDecimal.valueOf(Long.parseLong(tPriceRecord1.getRecordNo().toString()) + 1));
                }
                tPriceRecord.setDataFrom(plantId);
                itPriceRecordService.save(tPriceRecord);
            }
            sysLogBu.logRecord("产品调价", user.getTrueName(), String.valueOf(logMsg), plantId);
            return SzResult.success("修改成功");
        } else {
            return SzResult.error("用户不存在");
        }
    }

    @Async
    public Future<List<PdtAuthExcelEn>> pdtAuthExportExcel(List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, boolean isHeader, String mode, Boolean original, Map<String, String> pager, String sheetName, String plantId, String pdtsauthCo, String pdtsauthPdt) {

        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<PdtAuthExcelEn> list = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        PdtAuthExcelEn pdtAuthExcelEn = PdtAuthExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("pdtsauthCo")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthCo(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthPdt")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthPdt(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtsauthPrice")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthPrice(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthOprtr")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthOprtr(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthTime")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthReason")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthReason(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtsauthLock")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthLock(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(pdtAuthExcelEn);
                    }
                    break;
                case "all":
                    QueryWrapper<CPdtsAuth> queryWrapper = new QueryWrapper<>();
                    queryWrapper.like(pdtsauthCo != null && !pdtsauthCo.equals(""), "PDTSAUTH_CO", pdtsauthCo);
                    queryWrapper.like(pdtsauthPdt != null && !pdtsauthPdt.equals(""), "PDTSAUTH_PDT", pdtsauthPdt);
                    queryWrapper.eq("PDTSAUTH_DELETED", 0);
                    queryWrapper.eq("DATA_FROM", plantId);
                    List<CPdtsAuth> cPdtsAuths = iCPdtsAuthService.list(queryWrapper);
                    for (CPdtsAuth cPdtsAuth : cPdtsAuths) {
                        PdtAuthExcelEn pdtAuthExcelEn = PdtAuthExcelEn.builder()
                                .pdtsauthCo(Optional.of(cPdtsAuth.getPdtsauthCo()+"."+cPdtsAuth.getPdtsauthChico()).orElse(""))
                                .pdtsauthPdt(Optional.ofNullable(cPdtsAuth.getPdtsauthPdt()).orElse(""))
                                .pdtsauthPrice(Optional.ofNullable(cPdtsAuth.getPdtsauthPrice()).map(Object::toString).orElse(""))
                                .pdtsauthOprtr(Optional.ofNullable(cPdtsAuth.getPdtsauthOprtr()).map(Object::toString).orElse(""))
                                .pdtsauthTime(Optional.ofNullable(cPdtsAuth.getPdtsauthTime()).map(Object::toString).orElse(""))
                                .pdtsauthReason(Optional.ofNullable(cPdtsAuth.getPdtsauthReason()).map(Object::toString).orElse(""))
                                .pdtsauthApprver(Optional.ofNullable(cPdtsAuth.getPdtsauthApprver()).map(Object::toString).orElse(""))
                                .pdtsauthApprvTm(Optional.ofNullable(cPdtsAuth.getPdtsauthApprvTm()).map(Object::toString).orElse(""))
                                .pdtsauthApprver2(Optional.ofNullable(cPdtsAuth.getPdtsauthApprver2()).map(Object::toString).orElse(""))
                                .pdtsauthApprvTm2(Optional.ofNullable(cPdtsAuth.getPdtsauthApprvTm2()).map(Object::toString).orElse(""))
                                .pdtsauthApprved(Optional.ofNullable(pdtAuthDic.getPdtAuthApprovedDic(cPdtsAuth.getPdtsauthApprved())).map(Object::toString).orElse(""))
                                .pdtsauthApprved2(Optional.ofNullable(pdtAuthDic.getPdtAuthApproved2Dic(cPdtsAuth.getPdtsauthApprved2())).map(Object::toString).orElse(""))
                                .pdtsauthLock(Optional.ofNullable(pdtAuthDic.getPdtAuthLockDic(cPdtsAuth.getPdtsauthLock())).orElse(""))
                                .build();
                        list.add(pdtAuthExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为NoticeExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        PdtAuthExcelEn pdtAuthExcelEn = PdtAuthExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {

                            if (entry.getKey().equals("pdtsauthCo")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthCo(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthPdt")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthPdt(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtsauthPrice")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthPrice(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthOprtr")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthOprtr(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthTime")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthTime(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("pdtsauthReason")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthReason(entry.getValue().toString());
                                }
                            }
//                           trucksTrailerno
                            if (entry.getKey().equals("pdtsauthLock")) {
                                if (entry.getValue() != null) {
                                    pdtAuthExcelEn.setPdtsauthLock(entry.getValue().toString());
                                }
                            }
                        }
                        list.add(pdtAuthExcelEn);
                    }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(list);
    }

    //冻结品种授权
    @Transactional
    public SzResult freezePdtAuth(String id, Integer lock, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        if (user != null) {
            CPdtsAuth cPdtsAuth = iCPdtsAuthService.getById(id);
            if (cPdtsAuth != null) {
                if (lock == 1) {
                    cPdtsAuth.setPdtsauthReason(LocalDateTime.now() + "由" + user.getTrueName() + "冻结");
                    sysLogBu.logRecord("冻结品种授权", user.getTrueName(), "冻结" + cPdtsAuth.getPdtsauthCo() + "的" + cPdtsAuth.getPdtsauthPdt(), plantId);
                } else {
                    cPdtsAuth.setPdtsauthReason(LocalDateTime.now() + "由" + user.getTrueName() + "解冻");
                    sysLogBu.logRecord("解冻品种授权", user.getTrueName(), "解冻" + cPdtsAuth.getPdtsauthCo() + "的" + cPdtsAuth.getPdtsauthPdt(), plantId);
                }
                cPdtsAuth.setPdtsauthLock(lock);
                cPdtsAuth.setDownedID1(0);
                boolean b = iCPdtsAuthService.updateById(cPdtsAuth);
                if (b) {
                    return SzResult.Success();
                } else {
                    return SzResult.error("修改失败");
                }
            } else {
                return SzResult.error("该授权不存在");
            }
        } else {
            return SzResult.error("用户不存在");
        }
    }

    //删除授权品种
    public SzResult deletePdtAuth(String id, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        if (user != null) {
            CPdtsAuth cPdtsAuth = iCPdtsAuthService.getById(id);
            if (cPdtsAuth != null) {
                String pdtsauthPdt = cPdtsAuth.getPdtsauthPdt();
                QueryWrapper<CProductsInfo> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("PDTINF_PDT", pdtsauthPdt);
                queryWrapper.eq("PDTINF_DELETED", 0);
                queryWrapper.eq("DATA_FROM", plantId);
                CProductsInfo cProductsInfo = iCProductsInfoService.getOne(queryWrapper);
                String id1 = String.valueOf(cProductsInfo.getPdtinfId());
                QueryWrapper<CTrucks> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("TRUCKS_CHECKIN_PDT", id1);
                queryWrapper1.eq("TRUCKS_DELETED", 0);
                queryWrapper1.eq("DATA_FROM", plantId);
                queryWrapper1.between("TRUCKS_QUEUE_STATUS", 1, 6);
                queryWrapper1.last("limit 1");
                CTrucks cTrucks = iCTrucksService.getOne(queryWrapper1);
                if (cTrucks != null) {
                    return SzResult.error("厂内有车辆正在运行，请等待车辆出厂后再操作。");
                }

                cPdtsAuth.setPdtsauthReason(LocalDateTime.now() + "由" + user.getTrueName() + "删除");
                sysLogBu.logRecord("删除品种授权", user.getTrueName(), "删除" + cPdtsAuth.getPdtsauthCo() + "的" + pdtsauthPdt, plantId);
                cPdtsAuth.setPdtsauthDeleted(1);
                cPdtsAuth.setDownedID1(0);
                boolean b = iCPdtsAuthService.updateById(cPdtsAuth);
                if (b) {
                    return SzResult.Success();
                } else {
                    return SzResult.error("修改失败");
                }
            } else {
                return SzResult.error("该授权不存在");
            }
        } else {
            return SzResult.error("用户不存在");
        }
    }

    //调价记录查询
    public SzResult getPriceRecord(Integer page, Integer pageSize, String startTime, String endTime, BigDecimal recordNo, String pdtId, String cpyId, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        // String plantId = plantId;
        if (user != null) {
            if (page != null && pageSize != null) {
                Page<TPriceRecord> page1 = new Page<>(page, pageSize);
                QueryWrapper<TPriceRecord> queryWrapper = new QueryWrapper<>();
                if (startTime != null && !startTime.equals("") && endTime != null && !endTime.equals("")) {
                    queryWrapper.between("CREATE_TIME", startTime, endTime);
                }
                queryWrapper.like(recordNo != null, "RECORD_NO", recordNo);
                queryWrapper.eq(pdtId != null && !pdtId.equals(""), "PDT_ID", pdtId);
                queryWrapper.eq(cpyId != null && !cpyId.equals(""), "CPY_ID", cpyId);
                queryWrapper.eq("DATA_FROM", plantId);
                queryWrapper.orderByDesc("CREATE_TIME").orderByDesc("RECORD_NO");
                List<TPriceRecord> list1 = itPriceRecordService.page(page1, queryWrapper).getRecords();
                List<GetPriceRecordVo> list = new ArrayList<>();
                for (TPriceRecord tPriceRecord : list1) {
                    GetPriceRecordVo getPriceRecordVo = tPriceRecord2GetPriceRecordVo.priceRecord2GetPriceRecordVo(tPriceRecord);
                    list.add(getPriceRecordVo);
                }
                Map<String, Object> map = new HashMap<>();
                map.put("total", itPriceRecordService.page(page1, queryWrapper).getTotal());
                map.put("list", list);
                return SzResult.success(map);
            } else {
                QueryWrapper<TPriceRecord> queryWrapper = new QueryWrapper<>();
                if (startTime != null && !startTime.equals("") && endTime != null && !endTime.equals("")) {
                    queryWrapper.between("CREATE_TIME", startTime, endTime);
                }
                queryWrapper.eq(pdtId != null && !pdtId.equals(""), "PDT_ID", pdtId);
                queryWrapper.eq(cpyId != null && !cpyId.equals(""), "CPY_ID", cpyId);
                queryWrapper.eq("DATA_FROM", plantId);
                queryWrapper.orderByDesc("CREATE_TIME");
                List<TPriceRecord> list1 = itPriceRecordService.list(queryWrapper);
                List<GetPriceRecordVo> list = new ArrayList<>();
                for (TPriceRecord tPriceRecord : list1) {
                    GetPriceRecordVo getPriceRecordVo = tPriceRecord2GetPriceRecordVo.priceRecord2GetPriceRecordVo(tPriceRecord);
                    list.add(getPriceRecordVo);
                }
                Map<String, Object> map = new HashMap<>();
                map.put("total", list.size());
                map.put("list", list);
                return SzResult.success(map);
            }
        } else {
            return SzResult.error("用户不存在");
        }
    }

    //    修改调价信息的备注updatePriceRecord
    public SzResult updatePriceRecord(String id, String remark, String token, String plantId) throws Exception {
        SysUser user = userInfoDao.getUser(StpUtil.getLoginIdByToken(token).toString());
        if (user != null) {
            TPriceRecord tPriceRecord = itPriceRecordService.getById(id);
            if (tPriceRecord != null) {
                tPriceRecord.setRemark(remark);
                boolean b = itPriceRecordService.updateById(tPriceRecord);
                if (b) {
                    sysLogBu.logRecord("修改调价备注", user.getTrueName(), "修改调价编号为" + tPriceRecord.getRecordNo() + "的备注", plantId);
                    return SzResult.Success();
                } else {
                    return SzResult.error("修改失败");
                }
            } else {
                return SzResult.error("该调价记录不存在");
            }
        } else {
            return SzResult.error("用户不存在");
        }
    }


    /**
     * 导表
     */
    @Async
    public Future<List<GetPriceRecordExcelEn>> priceRecordExportExcel(List<Map<String, Object>> fields, String filename, List<Map<String, Object>> ids, Boolean isHeader, String mode, Boolean original, Map<String, String> pager, String sheetName, String pdtId, String cpyId, String recordNo, String plantId, String startTime, String endTime) throws Exception {
        List<Map<String, Object>> newIds = new ArrayList<>();
//        最终数据
        List<GetPriceRecordExcelEn> list = new ArrayList<>();
        try {
            switch (mode) {
                case "current":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为AshGateExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        GetPriceRecordExcelEn getPriceRecordExcelEn = GetPriceRecordExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
//
                            if (entry.getKey().equals("price")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setPrice(BigDecimal.valueOf(Long.parseLong(entry.getValue().toString())));
                                }
                            }
                            if (entry.getKey().equals("pdtName")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setPdtName(entry.getValue().toString());
                                }
                            }
//
                            if (entry.getKey().equals("cpyName")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setCpyName(entry.getValue().toString());
                                }
                            }
//
                            if (entry.getKey().equals("creatorName")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setCreatorName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("createTime")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {

                                    getPriceRecordExcelEn.setCreateTime(LocalDateTime.parse(entry.getValue().toString().replace(" ", "T")));
                                }
                            }
//
                            if (entry.getKey().equals("remark")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setRemark(entry.getValue().toString());
                                }
                            }
//                                trucksAxles
                            if (entry.getKey().equals("recordNo")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setRecordNo(BigDecimal.valueOf(Long.parseLong(entry.getValue().toString())));
                                }
                            }
                        }
                        list.add(getPriceRecordExcelEn);
                    }
                    break;
                case "all":
                    QueryWrapper<TPriceRecord> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq(pdtId != null && !pdtId.equals(""), "PDT_ID", pdtId);
                    queryWrapper.eq(cpyId != null && !cpyId.equals(""), "CPY_ID", cpyId);
                    queryWrapper.eq(plantId != null && !plantId.equals(""), "DATA_FROM", plantId);
                    queryWrapper.eq(recordNo != null && !recordNo.equals(""), "RECORD_NO", recordNo);
                    queryWrapper.between(startTime != null && !startTime.equals("") && endTime != null && !endTime.equals(""), "CREATE_TIME", startTime, endTime);
                    queryWrapper.orderByDesc("CREATE_TIME");
                    List<TPriceRecord> tPriceRecords = itPriceRecordService.list(queryWrapper);
                    for (TPriceRecord tPriceRecord : tPriceRecords) {
                        BigDecimal bigDecimal = new BigDecimal(String.valueOf(tPriceRecord.getPrice()));
                        BigDecimal bigDecimal1 = new BigDecimal(String.valueOf(tPriceRecord.getRecordNo()));
                        CCompanys companys = icCompanysService.getById(tPriceRecord.getCpyId());
                        GetPriceRecordExcelEn getPriceRecordExcelEn = GetPriceRecordExcelEn.builder()
                                .pdtName(Optional.ofNullable((icProductsInfoService.getById(tPriceRecord.getPdtId())).getPdtinfPdt()).map(Object::toString).orElse(""))
                                .price(Optional.of(bigDecimal).orElse(BigDecimal.valueOf(0)))
                                .cpyName(Optional.of((companys).getCpyCo()+"."+companys.getCpyChico()).map(Object::toString).orElse(""))
                                .creatorName(Optional.ofNullable(tPriceRecord.getCreatorName()).map(Object::toString).orElse(""))
                                .createTime(LocalDateTime.parse(Optional.ofNullable(tPriceRecord.getCreateTime()).map(Object::toString).orElse("")))
                                .remark(Optional.ofNullable(tPriceRecord.getRemark()).map(Object::toString).orElse(""))
                                .recordNo(Optional.of(bigDecimal1).orElse(BigDecimal.valueOf(0)))
                                .build();
                        list.add(getPriceRecordExcelEn);
                    }
                    break;
                case "selected":
                    for (Map<String, Object> id : ids) {
                        Map<String, Object> newId = new HashMap<>();
                        for (Map<String, Object> field : fields) {
                            if (id.containsKey(field.get("field"))) {
                                newId.put(field.get("field").toString(), id.get(field.get("field")));
                            }
                        }
                        newIds.add(newId);
                    }
//             newIds为Map<String, Object>类型,需要转换为AshGateExcelEn类型
                    for (Map<String, Object> newId : newIds) {
                        GetPriceRecordExcelEn getPriceRecordExcelEn = GetPriceRecordExcelEn.builder().build();
                        for (Map.Entry<String, Object> entry : newId.entrySet()) {
//
                            if (entry.getKey().equals("price")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setPrice(BigDecimal.valueOf(Long.parseLong(entry.getValue().toString())));
                                }
                            }
                            if (entry.getKey().equals("pdtName")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setPdtName(entry.getValue().toString());
                                }
                            }
//
                            if (entry.getKey().equals("cpyName")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setCpyName(entry.getValue().toString());
                                }
                            }
//
                            if (entry.getKey().equals("creatorName")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setCreatorName(entry.getValue().toString());
                                }
                            }
                            if (entry.getKey().equals("createTime")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setCreateTime(LocalDateTime.parse(entry.getValue().toString().replace(" ", "T")));
                                }
                            }
//
                            if (entry.getKey().equals("remark")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setRemark(entry.getValue().toString());
                                }
                            }
//                                trucksAxles
                            if (entry.getKey().equals("recordNo")) {
                                if (entry.getValue() != null && !entry.getValue().equals("")) {
                                    getPriceRecordExcelEn.setRecordNo(BigDecimal.valueOf(Long.parseLong(entry.getValue().toString())));
                                }
                            }
                        }
                        list.add(getPriceRecordExcelEn);
                    }


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AsyncResult<>(list);
    }

    public void updatePrices() {
        // 创建查询条件
        QueryWrapper<CPdtsAuth> cPdtsAuthQueryWrapper = new QueryWrapper<>();
        cPdtsAuthQueryWrapper.eq("PDTSAUTH_DELETED", 0);

        // 查询符合条件的数据
        List<CPdtsAuth> cPdtsAuthList = icPdtsAuthService.list(cPdtsAuthQueryWrapper);

        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        for (CPdtsAuth cPdtsAuth : cPdtsAuthList) {
            // 获取两个预调价的时间和价格
            LocalDateTime preStartTime1 = cPdtsAuth.getPdtsauthPreStartTime();
            BigDecimal prePrice1 = cPdtsAuth.getPdtsauthPrePrice();
            String preOprtr1 = cPdtsAuth.getPdtsauthPreOprtr();
            LocalDateTime preTime1 = cPdtsAuth.getPdtsauthPreTime();

            LocalDateTime preStartTime2 = cPdtsAuth.getPdtsauthPreStartTime2();
            BigDecimal prePrice2 = cPdtsAuth.getPdtsauthPrePrice2();
            String preOprtr2 = cPdtsAuth.getPdtsauthPreOprtr2();
            LocalDateTime preTime2 = cPdtsAuth.getPdtsauthPreTime2();

            // 确定应该使用的预调价
            if (preStartTime1 != null && prePrice1 != null && preStartTime1.isBefore(now)) {
                if (preStartTime2 != null && prePrice2 != null && preStartTime2.isBefore(now)) {
                    // 两个时间都在当前时间之前，选择较晚的那个
                    if (preStartTime2.isAfter(preStartTime1)) {
                        applyPriceUpdate(cPdtsAuth, prePrice2, preOprtr2, preTime2);
                    } else {
                        applyPriceUpdate(cPdtsAuth, prePrice1, preOprtr1, preTime1);
                    }
                } else {
                    // 只有第一个预调价时间在当前时间之前
                    applyPriceUpdate(cPdtsAuth, prePrice1, preOprtr1, preTime1);
                }
            } else if (preStartTime2 != null && prePrice2 != null && preStartTime2.isBefore(now)) {
                // 只有第二个预调价时间在当前时间之前
                applyPriceUpdate(cPdtsAuth, prePrice2, preOprtr2, preTime2);
            }
        }
    }

    private void applyPriceUpdate(CPdtsAuth cPdtsAuth, BigDecimal newPrice, String operator, LocalDateTime updateTime) {
        // 检查新价格是否与当前价格不同
        if (newPrice != null && !newPrice.equals(cPdtsAuth.getPdtsauthPrice())) {
            CPdtsAuth updatedPdtsAuth = new CPdtsAuth();
            updatedPdtsAuth.setId(cPdtsAuth.getId());
            updatedPdtsAuth.setPdtsauthPrice(newPrice);
            updatedPdtsAuth.setPdtsauthOprtr(operator);
            updatedPdtsAuth.setPdtsauthTime(updateTime);

            // 更新数据
            icPdtsAuthService.updateById(updatedPdtsAuth);
        }
    }
}
